﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using System.Xml;
using fqlmoney.Common;
using fqlmoney.Model;
using fqlmoney.BLL;
using System.IO;

namespace fqlmoney.Controllers
{
    public class OauthController : Controller
    {

        /// <summary>
        /// 跳转到qq授权页面
        /// </summary>
        /// <returns></returns>
        public ActionResult qqlogin()
        {
            //获取配置文件
            XmlNodeList nodelist= XmlHelper.ReadNodes(Directory.GetCurrentDirectory() + "/wwwroot/config/oauth_qq.config","config");
            string appid = nodelist[0].InnerText;
            string redirectURI = nodelist[1].InnerText;
            StringBuilder url = new StringBuilder();
            url.Append("https://graph.qq.com/oauth2.0/authorize?");
            url.AppendFormat("client_id={0}", appid);
            url.AppendFormat("&redirect_uri={0}", redirectURI);
            url.AppendFormat("&scope=get_user_info,list_album,upload_pic,add_feeds,do_like");
            url.AppendFormat("&response_type=code");
            return Redirect(url.ToString());
        }
        /// <summary>
        /// qq登录回调
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public ActionResult qq(string code)
        {

            //获取配置文件
            try
            {
                XmlNodeList nodelist = XmlHelper.ReadNodes(Directory.GetCurrentDirectory() + "/wwwroot/config/oauth_qq.config", "config");
                string appid = nodelist[0].InnerText;
                string appkey = nodelist[2].InnerText;
                string redirectURI = nodelist[1].InnerText;
                StringBuilder url = new StringBuilder();
                //获取token
                url.AppendFormat("https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id={0}&client_secret={1}&code={2}&redirect_uri={3}", appid, appkey, code, redirectURI);

                string resp = Common.HttpRequest.Get(url.ToString()).Result;
                string token = resp.Split('&')[0].Split('=')[1];
                //获取openid
                url.Clear();
                url.AppendFormat("https://graph.qq.com/oauth2.0/me?access_token={0}", token);

                resp = Common.HttpRequest.Get(url.ToString()).Result;

                oauth_qq_openid qqopen = JSONHelper.DeserializeJsonToObject<oauth_qq_openid>(resp.Replace("callback(", "").Replace(");", ""));
                if (qqopen.client_id == appid)
                {
                    UserInfoBLL bll = new UserInfoBLL();
                  
                    //判断是否存在
                    userinfo model = bll.GetModelByQQOpenid(qqopen.openid);

                    if (model!=null)
                    {
                        HttpContext.Session.SetString("fqlmoneyuser", JSONHelper.SerializeObject(model));
                        string value = "QQ|"+model.qq_openid;
                        Response.Cookies.Append("fqlmoneyuser", Utils.AESEncrypt(value), new CookieOptions { Path = "/", Expires = DateTime.Now.AddMonths(1) });
                        return Redirect("/");
                        
                    }
                    else
                    {
                        url.Clear();
                        //获取用户信息
                        url.AppendFormat("https://graph.qq.com/user/get_user_info?access_token={0}&oauth_consumer_key={1}&openid={2}", token, appid, qqopen.openid);

                        resp = Common.HttpRequest.Get(url.ToString()).Result;
                        //获取到的信息转成对象(返回内容请看文档)
                        oauth_qq_userinfo info = JSONHelper.DeserializeJsonToObject<oauth_qq_userinfo>(resp);
                        if (info.ret == 0)
                        {
                            model = new userinfo();
                            model.u_name = info.nickname;
                            model.qq_openid = qqopen.openid;
                            model.weibo_openid = "";
                            model.weixin_openid = "";
                            model.u_headimg =Common.HttpRequest.Get_img(info.figureurl_qq_1).Result;
                            //把内容写进去
                            bll.AddUser(model);
                            //重新获取userinfo
                            model = bll.GetModelByQQOpenid(qqopen.openid);
                            HttpContext.Session.SetString("fqlmoneyuser", JSONHelper.SerializeObject(model));
                            string value = "QQ|" + model.qq_openid;
                            Response.Cookies.Append("fqlmoneyuser", Utils.AESEncrypt(value), new CookieOptions { Path = "/", Expires = DateTime.Now.AddMonths(1) });
                            return Redirect("/");

                        }
                        else
                        {
                            LogHelper.Error("qq登录回调报错_获取用户信息", JSONHelper.SerializeObject(info));
                        }
                    }
                }
                else
                {
                    LogHelper.Error("qq登录回调报错_获取openid", JSONHelper.SerializeObject(qqopen));
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error("qq登录回调报错", ex.ToString());
            }
            return View();
        }



        /// <summary>
        /// 跳转到weibo授权页面
        /// </summary>
        /// <returns></returns>
        public ActionResult wblogin()
        {
            //获取配置文件
            XmlNodeList nodelist = XmlHelper.ReadNodes(Directory.GetCurrentDirectory() + "/wwwroot/config/oauth_weibo.config", "config");
            string appkey = nodelist[0].InnerText;
            string redirectURI = nodelist[1].InnerText;
            StringBuilder url = new StringBuilder();
            url.Append("https://api.weibo.com/oauth2/authorize?");
            url.AppendFormat("client_id={0}", appkey);
            url.AppendFormat("&redirect_uri={0}", redirectURI);
            url.AppendFormat("&scope=all");
            url.AppendFormat("&response_type=code");
            return Redirect(url.ToString());
        }
        /// <summary>
        /// weibo登录回调
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public ActionResult weibo(string code)
        {
            //获取配置文件
            try
            {
                XmlNodeList nodelist = XmlHelper.ReadNodes(Directory.GetCurrentDirectory() + "/wwwroot/config/oauth_weibo.config", "config");
                string appkey = nodelist[0].InnerText;
                string AppSecret = nodelist[2].InnerText;
                string redirectURI = nodelist[1].InnerText;
                
                //获取token
                string token_data=string.Format("grant_type=authorization_code&client_id={0}&client_secret={1}&code={2}&redirect_uri={3}", appkey, AppSecret, code, redirectURI);
                string resp_token = Common.HttpRequest.Post(token_data, "https://api.weibo.com/oauth2/access_token").Result;
                oauth_weibo_token weibotoken = JSONHelper.DeserializeJsonToObject<oauth_weibo_token>(resp_token);
                if (weibotoken != null)
                {
                    UserInfoBLL bll = new UserInfoBLL();

                    //判断是否存在
                    userinfo model = bll.GetModelByWeiBoOpenid(weibotoken.access_token);

                    if (model != null)
                    {
                        HttpContext.Session.SetString("fqlmoneyuser", JSONHelper.SerializeObject(model));
                        string value = "WB|" + model.weibo_openid;
                        Response.Cookies.Append("fqlmoneyuser", Utils.AESEncrypt(value), new CookieOptions { Path = "/", Expires = DateTime.Now.AddMonths(1) });
                        return Redirect("/");
                    }
                    else
                    {
                        //获取用户信息
                        string url = string.Format("https://api.weibo.com/2/users/show.json?access_token={0}&uid={1}", weibotoken.access_token, weibotoken.uid);
                        string resp_user = Common.HttpRequest.Get(url).Result;
                        oauth_weibo_userinfo weibouser = JSONHelper.DeserializeJsonToObject<oauth_weibo_userinfo>(resp_user);


                        if (string.IsNullOrEmpty(weibouser.error))
                        {
                            model = new userinfo();
                            model.u_name = weibouser.screen_name;
                            model.qq_openid = "";
                            model.weibo_openid = weibotoken.access_token;
                            model.weixin_openid = "";
                            model.u_headimg = Common.HttpRequest.Get_img(weibouser.profile_image_url).Result;
                            //把内容写进去
                            bll.AddUser(model);
                            //重新获取userinfo
                            model = bll.GetModelByWeiBoOpenid(weibotoken.access_token);
                            HttpContext.Session.SetString("fqlmoneyuser", JSONHelper.SerializeObject(model));
                            string value = "WB|" + model.qq_openid;
                            Response.Cookies.Append("fqlmoneyuser", Utils.AESEncrypt(value), new CookieOptions { Path = "/", Expires = DateTime.Now.AddMonths(1) });
                            return Redirect("/");
                        }
                        else
                        {
                            LogHelper.Error("微博登录回调报错_获取用户信息", JSONHelper.SerializeObject(weibouser));
                        }
                    }
                }
                else
                {
                    LogHelper.Error("微博登录获取token报错", resp_token);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error("微博登录回调报错", ex.ToString());
            }
            return View();
        }

    }
}